﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using taigu.WeChat;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Microsoft.Extensions.Configuration;
using taigu.WebChat;
using Microsoft.AspNetCore.Authorization;

namespace taigu
{
    public partial class AdminService : ApplicationService, IAdminService
    {
        private readonly IRepository<WeChat.PostInfo, Guid> _postInfoRepository;
        private readonly IRepository<WeChat.WeChatUsers, Guid> _weChatUsersRepository;
        private readonly IRepository<WeChat.PostComments, Guid> _postCommentsRepository;
        private readonly IRepository<WeChat.PostLike, Guid> _postLikeRepository;
        private readonly IRepository<WeChat.OrganizationStruct, Guid> _organizationStructRepository;
        private readonly IRepository<Draw_log, Guid> _draw_log;
        private readonly IRepository<Address, Guid> _addresses;
        private readonly IRepository<Awards, Guid> _awards;
        public AdminService(IRepository<WeChat.PostInfo, Guid> postInfoRepository, IRepository<WeChat.WeChatUsers, Guid> weChatUsersRepository, IRepository<WeChat.PostComments, Guid> postCommentsRepository, IRepository<WeChat.PostLike, Guid> postLikeRepository, IRepository<WeChat.OrganizationStruct, Guid> organizationStructRepository, IRepository<Draw_log, Guid> draw_log, IRepository<Address, Guid> addresses, IRepository<Awards, Guid> awards, IConfiguration configuration)
        {
            this._configuration = configuration;
            this._postInfoRepository = postInfoRepository;
            _weChatUsersRepository = weChatUsersRepository;
            _postCommentsRepository = postCommentsRepository;
            _postLikeRepository = postLikeRepository;
            _organizationStructRepository = organizationStructRepository;
            imgHost = _configuration.GetSection("WxConfig:imgHost").Value;
            _draw_log = draw_log;
            _addresses = addresses;
            this._awards = awards;

        }
      

        private string imgHost = string.Empty;
        private IConfiguration _configuration;
        /// <summary>
        /// 后台帖子管理类
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost, Route("/admin/community/getPostList")]
        public ResData<object> GetCommunityPostList(PostInfoAdminDto dto)
        {
           
            try
            {
                var list = (from postinfo in _postInfoRepository
                            join wechatUser in _weChatUsersRepository
                            on postinfo.user_id equals wechatUser.Id
                            //  where wechatUser.status == UserStatus.enabled//2021-11-27只查询非黑名单帐号
                            select new PostInfoSelectDto()
                            {
                                avatarUrl = wechatUser.avatar_url,
                                buId = wechatUser.bu_id,
                                buName = _organizationStructRepository.Where(x => x.Id.ToString() == wechatUser.bu_id).FirstOrDefault().name,
                                companyId = wechatUser.company_id,
                                companyName = _organizationStructRepository.Where(x => x.Id.ToString() == wechatUser.company_id).FirstOrDefault().name,
                                commentsCount = _postCommentsRepository.Count(x => x.post_id == postinfo.Id),
                                likesCount = _postLikeRepository.Count(x => x.post_id == postinfo.Id && x.status == PostStatus.启用),
                                content = postinfo.content,
                                createTime = postinfo.CreationTime,
                                imageUrl = imgHost + postinfo.image_url,
                                //isLike = _postLikeRepository.Count(x => x.post_id == postinfo.Id.ToString() && x.user_id == dto.user_id && x.status == PostStatus.启用) > 0,
                                nickName = wechatUser.nick_name,
                                postId = postinfo.Id.ToString(),
                                realName = wechatUser.real_name,
                                status = postinfo.status,
                                user_id = wechatUser.Id,
                                post_order = postinfo.post_order
                            }
                            );
                if (!string.IsNullOrEmpty(dto.buId))
                    list = list.Where(x => x.buId == dto.buId);
                if (!string.IsNullOrEmpty(dto.companyId))
                    list = list.Where(x => x.companyId == dto.companyId);

                if (dto.status == PostStatus.删除)
                {
                    list = list.Where(x => x.status == PostStatus.删除);
                }
                if (dto.status == PostStatus.启用)
                {
                    list = list.Where(x => x.status == PostStatus.启用);
                }

                if (dto.orderBy == "likes")
                {
                    if (dto.order == DataOrderType.asc)
                    {
                        list = list.OrderByDescending(x => x.post_order).ThenBy(x => x.likesCount).ThenByDescending(x => x.createTime);
                    }
                    else
                    {
                        list = list.OrderByDescending(x => x.post_order).ThenByDescending(x => x.likesCount).ThenByDescending(x => x.createTime);
                    }
                }
                if (dto.orderBy == "date")
                {
                    if (dto.order == DataOrderType.asc)
                    {
                        list = list.OrderByDescending(x => x.post_order).ThenBy(x => x.createTime);
                    }
                    else
                    {
                        list = list.OrderByDescending(x => x.post_order).ThenByDescending(x => x.createTime);
                    }
                }

                int count = list.Count();

                if (dto.page < 0)
                    dto.page = 1;
                if (dto.pageSize < 0)
                    dto.pageSize = 10;
                list = list.Skip((dto.page - 1) * dto.pageSize).Take(dto.pageSize);


                return new ResData<object>() { Status = ResStatus.成功, Msg = "sucess", Info = new { count = count, list = list.ToList() } };
            }
            catch (Exception ex)
            {
                return new ResData<object>() { Status = ResStatus.查询失败, Msg = ex.Message, Info = null };
            }
        }



        [Route("admin/community/postStatus"), HttpPost]
        public async Task<ResData<string>> postStatus(PostDto m)
        {
            try
            {

                PostInfo model = await _postInfoRepository.FirstOrDefaultAsync(x => x.Id == m.Post_id);
                if (model == null)
                {
                    return new ResData<string>() { Status = ResStatus.failed, Msg = "sucess", Info = "" };
                }
                else
                {
                    if (model.status == PostStatus.删除)
                        model.status = PostStatus.启用;
                    else
                        model.status = PostStatus.删除;
                    await _postInfoRepository.UpdateAsync(model);
                    return new ResData<string>() { Status = ResStatus.成功, Msg = "sucess", Info = "" };
                }
            }
            catch (Exception ex)
            {
                return new ResData<string>() { Status = ResStatus.failed, Msg = ex.Message, Info = "" };
            }
        }
        [Route("admin/community/postCommentStatus"), HttpPost]
        public async Task<ResData<string>> postCommentStatus(PostCommentDto m)
        {
            try
            {

                PostComments model = await _postCommentsRepository.FirstOrDefaultAsync(x => x.Id == m.comment_id);
                if (model == null)
                {
                    return new ResData<string>() { Status = ResStatus.failed, Msg = "sucess", Info = "" };
                }
                else
                {
                    if (model.status == PostStatus.删除)
                        model.status = PostStatus.启用;
                    else
                        model.status = PostStatus.删除;
                    await _postCommentsRepository.UpdateAsync(model);
                    return new ResData<string>() { Status = ResStatus.成功, Msg = "sucess", Info = "" };
                }
            }
            catch (Exception ex)
            {
                return new ResData<string>() { Status = ResStatus.failed, Msg = ex.Message, Info = "" };
            }
        }

        [Route("admin/community/postAndComments"), HttpPost]
        public  ResData<object> postAndComment(PostDto m)
        {
            try
            {

                var list = (from postinfo in _postInfoRepository
                            join wechatUser in _weChatUsersRepository
                            on postinfo.user_id equals wechatUser.Id
                            select new PostInfoSelectDto()
                            {
                                avatarUrl = wechatUser.avatar_url,
                                buId = wechatUser.bu_id,
                                buName = _organizationStructRepository.Where(x => x.Id.ToString() == wechatUser.bu_id).FirstOrDefault().name,
                                companyId = wechatUser.company_id,
                                companyName = _organizationStructRepository.Where(x => x.Id.ToString() == wechatUser.company_id).FirstOrDefault().name,
                                content = postinfo.content,
                                createTime = postinfo.CreationTime,
                                imageUrl = imgHost+postinfo.image_url,
                                nickName = wechatUser.nick_name,
                                realName = wechatUser.real_name,
                                postId = postinfo.Id.ToString(),
                                status = postinfo.status,
                                user_id = wechatUser.Id,
                                post_order = postinfo.post_order

                            }
                              );

                var model = list.Where(x => x.postId == m.Post_id.ToString()).FirstOrDefault();
                if (model == null)
                {
                    return new ResData<object>() { Status = ResStatus.failed, Msg = "sucess", Info = "" };
                }
                else
                {
                   // List<PostComments> comments = _postCommentsRepository.Where(x => x.post_id == model.postId.ToString())?.ToList();


                    List<PostCommentsShowDto> comments = (from Comment in _postCommentsRepository
                                 join user in _weChatUsersRepository
                                 on Comment.user_id equals user.Id
                                 where user.Id.Equals(Comment.user_id) 
                                 && Comment.post_id.Equals(model.postId)
                                 select new PostCommentsShowDto
                                 {
                                     nickName = user.nick_name,
                                     realName = user.real_name,
                                     avatarUrl = user.avatar_url,
                                     comment_id = Comment.Id.ToString(),
                                     content = Comment.content,
                                     CreationTime = Comment.CreationTime,
                                     status=Comment.status

                                 }).OrderByDescending(x => x.CreationTime).ToList();



                    return new ResData<object>() { Status = ResStatus.成功, Msg = "sucess", Info = new { postdata = model, postcoments = comments } };




                }
            }
            catch (Exception ex)
            {
                return new ResData<object>() { Status = ResStatus.failed, Msg = ex.Message, Info = "" };
            }
        }
    }
}
